import {useAccountStore} from "./AccountStore.ts";
import {defineStore} from "pinia";
import type {NoticeBody} from "../network/types/Notice.ts";
import {ElMessage} from "element-plus";
import {CacheMap} from "../utils/CacheUtils.ts";

const api = () => useAccountStore().getNgaApi().notice

export const useNoticeStore = defineStore('NoticeStore', {
    state: () => ({
        cache: new CacheMap<NoticeBody>(),
    }),
    actions: {
        async list() {
            const userId = useAccountStore().getAccountUserId();
            const key = `notice ${userId}`
            const oldBody = this.cache.get(key);
            const newBody = await api().list(oldBody?.offset || 0);

            // 如果有旧数据，则合并
            if (oldBody) {
                newBody.replies = mergeArray(newBody.replies, oldBody.replies)
                newBody.messages = mergeArray(newBody.messages, oldBody.messages)
                newBody.likes = mergeArray(newBody.likes, oldBody.likes)
                newBody.offset = newBody.offset || oldBody.offset
            }
            this.cache.set(key, newBody)
            return newBody
        },
        async clear() {
            const userId = useAccountStore().getAccountUserId();
            const key = `notice ${userId}`
            const res = await api().clear();
            ElMessage.success(res.data)
            this.cache.delete(key)
        },
        enable(enable: boolean, tid: number, pid?: number | undefined) {
            return api().enable(enable, tid, pid)
        }
    },
})

const mergeArray = <T>(a1: T[] | undefined, a2: T[] | undefined) => {
    const res: T[] = []
    if (a1) res.push(...a1)
    if (a2) res.push(...a2)
    return res
}